<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>L1X图像预览</title>
    <script src="resources/chart.js"></script>
    <style>
        body { font-family: Arial, sans-serif; }
        #navbar { display: flex; gap: 20px; margin-bottom: 10px; }
        #preview{text-align: center;margin-top: 20px;}
        #preview img { max-width: 500px; max-height: 500px; }
        #previewImg { height: 510px; }
        .thumb { width: 200px; height: 200px; margin: 2px; cursor: pointer; }
        .thumb-container { display: flex; flex-wrap: wrap; }
        #loadThumbnailsButton { margin-top: 10px; padding: 5px 10px; cursor: pointer; }
        /* 固定 canvas 父容器的高度 */
        #chartContainer { height: 200px; }
        /* 弹出窗口样式 */
        #popup {
            position: fixed;
            top: 10px;
            left: 10px;
            width: 1200px;
            background: white;
            border: 1px solid #ccc;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 10px;
            z-index: 1000;
            display: none;
            cursor: move; /* 鼠标悬停时显示可拖动光标 */
        }
        #popup img { max-width: 500px; max-height: 500px; }
        /* 弹出窗口标题栏 */
        #popupHeader {
            padding: 5px;
            background: #f1f1f1;
            border-bottom: 1px solid #ccc;
            cursor: move; /* 鼠标悬停时显示可拖动光标 */
        }
        #closePopup {
            font-size: 20px;
            font-weight: bold;
            padding: 0 5px;
        }

        #closePopup:hover {
            color: red; /* 鼠标悬停时改变颜色 */
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div id="navbar">
        <select id="monthSelect"></select>
        <div id="dayList"></div>
    </div>
    <div style="text-align: center;"><h3>当前显示数据: <span id="dayShow">2025-03-23</span></h3></div>
    <!-- BGMEDIAN 曲线 -->
    <div id="chartContainer">
        <canvas id="bgmedianChart"></canvas>
    </div>

    <!-- 预览区 -->
    <div id="preview">
        <span id="imageInfo">请鼠标悬停在数据点上</span>
        <div id="previewImg"></div>
        <!-- 加载预览图像按钮 -->
        <button id="loadThumbnailsButton" style="display: none;">加载预览图像</button>
    </div>

    <!-- 弹出窗口 -->
    <div id="popup">
        <div id="popupHeader">
            图像详情 (拖动我)
            <span id="closePopup" style="float: right; cursor: pointer;">×</span>
        </div>
        <span id="popupImageInfo">请鼠标悬停在数据点上</span>
        <div id="popupImg"></div>
    </div>

    <!-- 预览图像流式显示 -->
    <div class="thumb-container" id="thumbs"></div>

    <script>
        const apiBase = "/api/vt";

        document.addEventListener("DOMContentLoaded", async () => {
            await loadMonths();
            setupPopupDrag(); // 初始化弹出窗口拖动功能
        });

        // 初始化弹出窗口拖动功能
        function setupPopupDrag() {
            const popup = document.getElementById("popup");
            const popupHeader = document.getElementById("popupHeader");
            const closePopup = document.getElementById("closePopup");

            let isDragging = false;
            let offsetX, offsetY;

            // 拖动功能
            popupHeader.addEventListener("mousedown", (e) => {
                if (e.target !== closePopup) { // 避免点击关闭按钮时触发拖动
                    isDragging = true;
                    offsetX = e.clientX - popup.offsetLeft;
                    offsetY = e.clientY - popup.offsetTop;
                }
            });

            document.addEventListener("mousemove", (e) => {
                if (isDragging) {
                    popup.style.left = `${e.clientX - offsetX}px`;
                    popup.style.top = `${e.clientY - offsetY}px`;
                }
            });

            document.addEventListener("mouseup", () => {
                isDragging = false;
            });

            // 关闭功能
            closePopup.addEventListener("click", () => {
                popup.style.display = "none"; // 隐藏弹窗
            });
        }

        async function loadMonths() {
            const response = await fetch(`${apiBase}/vtmonths`);
            const months = await response.json();
            const monthSelect = document.getElementById("monthSelect");

            monthSelect.innerHTML = months.map(month => `<option value="${month}">${month}</option>`).join("");
            monthSelect.addEventListener("change", () => loadDays(monthSelect.value));
            loadDays(months[0]);  // 加载最新月份
        }

        async function loadDays(month) {
            console.log("Loading days for month:", month);
            const response = await fetch(`${apiBase}/vtdays/${month}`);
            const days = await response.json();
            const dayList = document.getElementById("dayList");

            dayList.innerHTML = days.map(day => `<button onclick="loadData('${day}')">${day.split('-')[2]}</button>`).join("");
            if (days.length > 0) loadData(days[days.length - 1]); // 默认加载最新一天
        }

        async function loadData(date) {
            document.getElementById("dayShow").innerText = date;

            const response = await fetch(`${apiBase}/vtimgparms/${date}`);
            const data = await response.json();

            let images = [];

            for (let type in data) {
                for (let img of data[type].images) {
                    let timeParts = img["DATE-OBS"].split("T")[1].split(":");
                    let time = parseInt(timeParts[0]) + parseInt(timeParts[1]) / 60 + parseInt(timeParts[2]) / 3600;
                    images.push({ time, img });
                }
            }

            images.sort((a, b) => a.time - b.time);

            let timeHours = images.map(item => item.time);
            let bgMedian = images.map(item => item.img['image_info_r'] ? item.img['image_info_r']["BGMEDIAN"] : null);
            let sortedImages = images.map(item => item.img);

            plotChart(date, timeHours, bgMedian, sortedImages);

            // 默认显示第一个数据点的图像
            if (sortedImages.length > 0) {
                showPreview(sortedImages[0]);
            }

            // 显示“加载预览图像”按钮
            const loadThumbnailsButton = document.getElementById("loadThumbnailsButton");
            loadThumbnailsButton.style.display = "block";
            loadThumbnailsButton.onclick = () => showThumbnails(sortedImages);
        }

        function plotChart(date, timeHours, bgMedian, images) {
            const canvas = document.getElementById("bgmedianChart");
            const ctx = canvas.getContext("2d");

            // 显式设置 canvas 高度
            canvas.style.height = "200px";
            canvas.style.width = "100%";

            if (window.chartInstance) window.chartInstance.destroy();

            window.chartInstance = new Chart(ctx, {
                type: "line",
                data: {
                    labels: timeHours,
                    datasets: [{
                        label: "BGMEDIAN",
                        data: bgMedian,
                        borderColor: "red",
                        fill: false,
                        showLine: false,
                        pointRadius: 2,
                        pointBackgroundColor: "pink"
                    }]
                },
                options: {
                    responsive: true, // 允许响应式
                    maintainAspectRatio: false, // 禁用宽高比保持
                    scales: {
                        x: {
                            type: "linear",
                            position: "bottom",
                            ticks: {
                                stepSize: 1, // 刻度间隔为 1 小时
                                callback: function (value) {
                                    // 将小时数格式化为 HH:MM
                                    const hours = Math.floor(value);
                                    const minutes = Math.round((value - hours) * 60);
                                    return `${String(hours).padStart(2, '0')}`;
                                }
                            },
                            title: {
                                display: true,
                                text: "时间 (小时)"
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: (tooltipItem) => showPreview(images[tooltipItem.dataIndex])
                            }
                        }
                    }
                }
            });
        }

        function showPreview(img) {
            const preImgRootUrl = "/vt_images/L1X/preview/Imaging/";
            const relPath = img.fits_path;
            const rbandPath = `${preImgRootUrl}/${relPath}/${img.image_name_r.replace(".fit", "_origin.jpg")}`;
            const bbandPath = `${preImgRootUrl}/${relPath}/${img.image_name_b.replace(".fit", "_origin.jpg")}`;

            document.getElementById("imageInfo").innerText = `图像名称: ${img.image_name_r} | DATE-OBS: ${img["DATE-OBS"]} | BGMEDIAN: ${img['image_info_r']["BGMEDIAN"]}`;

            const previewContainer = document.getElementById("previewImg");
            previewContainer.innerHTML = "";

            const previewWrapper = document.createElement("div");
            previewWrapper.style.display = "flex";
            previewWrapper.style.justifyContent = "center";
            previewWrapper.style.gap = "10px";

            if (img.image_name_r) {
                const imgR = document.createElement("img");
                imgR.src = rbandPath;
                imgR.alt = "R 波段图";
                previewWrapper.appendChild(imgR);
            }

            if (img.image_name_b) {
                const imgB = document.createElement("img");
                imgB.src = bbandPath;
                imgB.alt = "B 波段图";
                previewWrapper.appendChild(imgB);
            }

            previewContainer.appendChild(previewWrapper);
        }

        function showThumbnails(images) {
            const preImgRootUrl = "/vt_images/L1X/preview/Imaging/";

            const thumbnails = document.getElementById("thumbs");
            thumbnails.innerHTML = images.map(img => {
                const relPath = img.fits_path;
                const thumbPath = `${preImgRootUrl}/${relPath}/${img.image_name_r.replace(".fit", ".jpg")}`;
                return `<img src="${thumbPath}" class="thumb" onclick='showPopup(${JSON.stringify(img)})'>`;
            }).join("");
        }

        function showPopup(img) {
            const popup = document.getElementById("popup");
            const popupImageInfo = document.getElementById("popupImageInfo");
            const popupImg = document.getElementById("popupImg");

            const preImgRootUrl = "/vt_images/L1X/preview/Imaging/";
            const relPath = img.fits_path;
            const rbandPath = `${preImgRootUrl}/${relPath}/${img.image_name_r.replace(".fit", "_origin.jpg")}`;
            const bbandPath = `${preImgRootUrl}/${relPath}/${img.image_name_b.replace(".fit", "_origin.jpg")}`;

            popupImageInfo.innerText = `图像名称: ${img.image_name_r} | DATE-OBS: ${img["DATE-OBS"]} | BGMEDIAN: ${img['image_info_r']["BGMEDIAN"]}`;

            popupImg.innerHTML = "";

            const popupWrapper = document.createElement("div");
            popupWrapper.style.display = "flex";
            popupWrapper.style.justifyContent = "center";
            popupWrapper.style.gap = "10px";

            if (img.image_name_r) {
                const imgR = document.createElement("img");
                imgR.src = rbandPath;
                imgR.alt = "R 波段图";
                popupWrapper.appendChild(imgR);
            }

            if (img.image_name_b) {
                const imgB = document.createElement("img");
                imgB.src = bbandPath;
                imgB.alt = "B 波段图";
                popupWrapper.appendChild(imgB);
            }

            popupImg.appendChild(popupWrapper);

            // 显示弹出窗口
            popup.style.display = "block";
        }
    </script>
</body>
</html>